// 全局变量
let token = localStorage.getItem('token');

// 带认证的fetch函数
async function fetchWithAuth(url, options = {}) {
    try {
        // 确保options.headers存在
        if (!options.headers) {
            options.headers = {};
        }
        
        // 添加token到请求头
        if (token) {
            options.headers['Authorization'] = `Bearer ${token}`;
        }
        
        // 执行fetch请求
        const response = await fetch(url, options);
        
        // 检查响应状态
        if (response.status === 401 || response.status === 403) {
            const data = await response.json();
            
            // 如果是token无效的错误
            if (data.error === '无效的令牌') {
                console.log('Token已过期，请重新登录');
                
                // 清除本地存储的认证信息
                localStorage.removeItem('token');
                localStorage.removeItem('userEmail');
                
                // 重定向到登录页面
                window.location.href = '/';
                
                return { response, error: '会话已过期，请重新登录' };
            }
            
            return { response, error: data.error };
        }
        
        // 尝试解析JSON响应
        let data;
        try {
            data = await response.json();
        } catch (e) {
            data = null;
        }
        
        return { response, data };
    } catch (error) {
        console.error('网络请求错误:', error);
        return { error: '网络请求失败，请检查网络连接' };
    }
}

// 初始化管理面板
function initAdminPanel() {
    try {
        // 设置侧边栏折叠按钮事件
        document.getElementById('toggleSidebar').addEventListener('click', toggleSidebar);
        
        // 设置退出登录按钮事件
        document.getElementById('logoutBtn').addEventListener('click', logout);
        
        // 检查管理员访问权限
        checkAdminAccess();
    } catch (error) {
        console.error('初始化管理面板错误:', error);
        document.getElementById('loading').innerHTML = `
            <div class="text-center">
                <p class="text-red-500 text-xl mb-4">初始化管理面板失败</p>
                <p class="text-gray-600">请刷新页面重试</p>
            </div>
        `;
    }
}

// 侧边栏收起/展开功能
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    
    sidebar.classList.toggle('collapsed');
    mainContent.classList.toggle('expanded');
}

// 注销功能
function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('userEmail');
    window.location.href = '/';
}

// 检查管理员访问权限
async function checkAdminAccess() {
    try {
        const { response, data, error } = await fetchWithAuth('/api/admin/check-access');
        
        if (error) {
            console.error('访问权限检查错误:', error);
            // 重定向到首页
            window.location.href = '/';
            return;
        }
        
        if (response && response.ok && data.hasAccess) {
            // 用户有访问权限，更新界面显示
            document.getElementById('loading').classList.add('hidden');
            document.getElementById('app').classList.remove('hidden');
            
            // 设置管理员信息
            const adminEmail = document.getElementById('adminEmail');
            const adminInitial = document.getElementById('adminInitial');
            
            if (adminEmail && adminInitial && data.email) {
                adminEmail.textContent = data.email;
                adminInitial.textContent = data.email.charAt(0).toUpperCase();
                
                // 根据角色设置不同样式
                const avatarContainer = adminInitial.parentElement;
                if (data.role === 'admin') {
                    avatarContainer.className = 'h-8 w-8 rounded-full bg-red-100 flex items-center justify-center mr-2';
                    adminInitial.className = 'text-red-600 font-medium';
                } else if (data.role === 'editor') {
                    avatarContainer.className = 'h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center mr-2';
                    adminInitial.className = 'text-blue-600 font-medium';
                }
            }
            
            // 根据角色限制访问
            if (data.role !== 'admin') {
                const usersTab = document.getElementById('usersTab');
                const settingsTab = document.getElementById('settingsTab');
                
                if (usersTab && settingsTab) {
                    usersTab.disabled = true;
                    usersTab.classList.add('opacity-50', 'cursor-not-allowed');
                    settingsTab.disabled = true;
                    settingsTab.classList.add('opacity-50', 'cursor-not-allowed');
                }
            }
            
            // 默认加载仪表盘
            loadDashboardTab();
        } else {
            console.error('无访问权限');
            // 重定向到首页
            window.location.href = '/';
        }
    } catch (error) {
        console.error('检查管理员访问错误:', error);
        // 重定向到首页
        window.location.href = '/';
    }
}

// 加载仪表盘标签页
function loadDashboardTab() {
    // 隐藏其他内容区域，显示仪表盘内容区域
    document.querySelectorAll('.content-area').forEach(area => {
        area.classList.add('hidden');
    });
    document.getElementById('dashboardPage').classList.remove('hidden');
    
    // 加载仪表盘数据
    loadDashboardData();
}

// 加载用户管理标签页
function loadUsersTab() {
    // 隐藏其他内容区域，显示用户内容区域
    document.querySelectorAll('.content-area').forEach(area => {
        area.classList.add('hidden');
    });
    document.getElementById('usersPage').classList.remove('hidden');
    
    // 加载用户数据
    loadUsersData();
}

// 加载仪表盘数据
async function loadDashboardData() {
    try {
        const { response, data, error } = await fetchWithAuth('/api/admin/dashboard');
        
        if (error) {
            console.error(error);
            document.getElementById('dashboardPage').innerHTML = `
                <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <i class="fas fa-exclamation-circle text-red-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-red-700">加载仪表盘数据失败: ${error}</p>
                        </div>
                    </div>
                </div>
            `;
            return;
        }
        
        if (response && response.ok) {
            // 渲染仪表盘页面
            document.getElementById('dashboardPage').innerHTML = `
                <h2 class="text-2xl font-bold mb-6">系统概览</h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="flex items-center">
                            <div class="p-3 rounded-full bg-blue-100 text-blue-500 mr-4">
                                <i class="fas fa-users"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">用户总数</p>
                                <p class="text-2xl font-semibold" id="totalUsers">0</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="flex items-center">
                            <div class="p-3 rounded-full bg-green-100 text-green-500 mr-4">
                                <i class="fas fa-list-check"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">习惯总数</p>
                                <p class="text-2xl font-semibold" id="totalHabits">0</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="flex items-center">
                            <div class="p-3 rounded-full bg-purple-100 text-purple-500 mr-4">
                                <i class="fas fa-check-double"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">已完成习惯</p>
                                <p class="text-2xl font-semibold" id="completedHabits">0</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="flex items-center">
                            <div class="p-3 rounded-full bg-yellow-100 text-yellow-500 mr-4">
                                <i class="fas fa-newspaper"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">文章总数</p>
                                <p class="text-2xl font-semibold" id="totalArticles">0</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <h3 class="text-lg font-semibold mb-4">最近注册的用户</h3>
                        <div class="overflow-x-auto">
                            <table class="min-w-full">
                                <thead>
                                    <tr>
                                        <th class="px-4 py-2 border-b text-left">ID</th>
                                        <th class="px-4 py-2 border-b text-left">邮箱</th>
                                        <th class="px-4 py-2 border-b text-left">注册时间</th>
                                    </tr>
                                </thead>
                                <tbody id="recentUsers">
                                    <tr>
                                        <td colspan="3" class="px-4 py-3 text-center text-gray-500">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <h3 class="text-lg font-semibold mb-4">最近创建的习惯</h3>
                        <div class="overflow-x-auto">
                            <table class="min-w-full">
                                <thead>
                                    <tr>
                                        <th class="px-4 py-2 border-b text-left">ID</th>
                                        <th class="px-4 py-2 border-b text-left">标题</th>
                                        <th class="px-4 py-2 border-b text-left">创建时间</th>
                                    </tr>
                                </thead>
                                <tbody id="recentHabits">
                                    <tr>
                                        <td colspan="3" class="px-4 py-3 text-center text-gray-500">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            `;
            
            // 填充数据
            renderDashboard(data);
        }
    } catch (error) {
        console.error('加载仪表盘数据错误:', error);
        document.getElementById('dashboardPage').innerHTML = '<p class="text-red-500">加载仪表盘数据失败</p>';
    }
}

// 渲染仪表盘
function renderDashboard(data) {
    // 设置统计数字
    document.getElementById('totalUsers').textContent = data.totalUsers || 0;
    document.getElementById('totalHabits').textContent = data.totalHabits || 0;
    document.getElementById('completedHabits').textContent = data.completedHabits || 0;
    document.getElementById('totalArticles').textContent = data.totalArticles || 0;
    
    // 渲染最近注册用户
    const recentUsersContainer = document.getElementById('recentUsers');
    recentUsersContainer.innerHTML = '';
    
    if (data.recentUsers && data.recentUsers.length > 0) {
        data.recentUsers.forEach(user => {
            const date = new Date(user.created_at);
            const formattedDate = date.toLocaleDateString();
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="px-4 py-3 border-b">${user.id}</td>
                <td class="px-4 py-3 border-b">${user.email}</td>
                <td class="px-4 py-3 border-b">${formattedDate}</td>
            `;
            recentUsersContainer.appendChild(row);
        });
    } else {
        recentUsersContainer.innerHTML = `
            <tr>
                <td colspan="3" class="px-4 py-3 text-center text-gray-500">暂无数据</td>
            </tr>
        `;
    }
    
    // 渲染最近创建的习惯
    const recentHabitsContainer = document.getElementById('recentHabits');
    recentHabitsContainer.innerHTML = '';
    
    if (data.recentHabits && data.recentHabits.length > 0) {
        data.recentHabits.forEach(habit => {
            const date = new Date(habit.created_at);
            const formattedDate = date.toLocaleDateString();
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="px-4 py-3 border-b">${habit.id}</td>
                <td class="px-4 py-3 border-b">${habit.title}</td>
                <td class="px-4 py-3 border-b">${formattedDate}</td>
            `;
            recentHabitsContainer.appendChild(row);
        });
    } else {
        recentHabitsContainer.innerHTML = `
            <tr>
                <td colspan="3" class="px-4 py-3 text-center text-gray-500">暂无数据</td>
            </tr>
        `;
    }
}

// 加载文章管理标签页
function loadArticlesTab() {
    // 隐藏其他内容区域，显示文章内容区域
    document.querySelectorAll('.content-area').forEach(area => {
        area.classList.add('hidden');
    });
    document.getElementById('articlesPage').classList.remove('hidden');
    
    // 加载文章数据
    loadArticlesData();
}

// 加载文章数据
async function loadArticlesData() {
    try {
        const articlesPage = document.getElementById('articlesPage');
        articlesPage.innerHTML = '<div class="text-center py-10"><i class="fas fa-spinner fa-spin text-green-500 text-2xl"></i></div>';
        
        const { response, data, error } = await fetchWithAuth('/api/admin/articles');
        
        if (error) {
            console.error('加载文章数据错误:', error);
            articlesPage.innerHTML = `<div class="text-center py-10 text-red-500">加载文章数据失败: ${error}</div>`;
            return;
        }
        
        if (response && response.ok) {
            renderArticlesAdmin(data.articles);
        } else {
            articlesPage.innerHTML = '<div class="text-center py-10 text-red-500">加载文章数据失败</div>';
        }
    } catch (error) {
        console.error('加载文章数据错误:', error);
        document.getElementById('articlesPage').innerHTML = '<div class="text-center py-10 text-red-500">服务器错误</div>';
    }
}

// 渲染文章管理页面
function renderArticlesAdmin(articles) {
    const articlesHTML = `
        <h2 class="text-2xl font-bold mb-6">文章管理</h2>
        
        <div class="mb-6 flex justify-end">
            <button id="addArticleBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center">
                <i class="fas fa-plus mr-2"></i> 添加文章
            </button>
        </div>
        
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">摘要</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">更新时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${articles && articles.length > 0 ? articles.map(article => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${article.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    ${article.title}
                                    ${article.is_pinned ? '<span class="ml-2 px-2 py-0.5 text-xs bg-red-100 text-red-800 rounded">置顶</span>' : ''}
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">${article.summary}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${new Date(article.updated_at).toLocaleString()}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    ${article.status === 'published' ? 
                                        '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">已发布</span>' : 
                                        '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">草稿</span>'
                                    }
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button class="text-indigo-600 hover:text-indigo-900 mr-3 edit-article-btn" data-id="${article.id}">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="text-red-600 hover:text-red-900 delete-article-btn" data-id="${article.id}">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </td>
                            </tr>
                        `).join('') : `
                            <tr>
                                <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">暂无文章数据</td>
                            </tr>
                        `}
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    document.getElementById('articlesPage').innerHTML = articlesHTML;
    
    // 添加事件监听
    document.getElementById('addArticleBtn').addEventListener('click', showAddArticleModal);
    
    document.querySelectorAll('.edit-article-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const articleId = this.getAttribute('data-id');
            editArticle(articleId);
        });
    });
    
    document.querySelectorAll('.delete-article-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const articleId = this.getAttribute('data-id');
            if (confirm('确定要删除这篇文章吗？')) {
                deleteArticle(articleId);
            }
        });
    });
}

// 显示添加文章模态框
function showAddArticleModal() {
    const modalHTML = `
        <div class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl h-5/6 flex flex-col">
                <div class="p-4 border-b flex justify-between items-center">
                    <h3 class="text-lg font-medium">添加文章</h3>
                    <button id="closeAddArticleBtn" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="p-4 flex-grow overflow-auto">
                    <form id="addArticleForm" class="space-y-4">
                        <div>
                            <label for="articleTitle" class="block text-sm font-medium text-gray-700 mb-1">文章标题</label>
                            <input type="text" id="articleTitle" name="title" class="w-full px-3 py-2 border rounded-md" required>
                        </div>
                        
                        <div>
                            <label for="articleSummary" class="block text-sm font-medium text-gray-700 mb-1">文章摘要</label>
                            <textarea id="articleSummary" name="summary" rows="2" class="w-full px-3 py-2 border rounded-md"></textarea>
                        </div>
                        
                        <div>
                            <label for="articleContent" class="block text-sm font-medium text-gray-700 mb-1">文章内容 (支持Markdown格式)</label>
                            <textarea id="articleContent" name="content" rows="15" class="w-full px-3 py-2 border rounded-md font-mono"></textarea>
                        </div>
                        
                        <div class="flex space-x-4">
                            <div class="flex items-center">
                                <input type="checkbox" id="articlePinned" name="is_pinned" class="mr-2">
                                <label for="articlePinned" class="text-sm text-gray-700">置顶文章</label>
                            </div>
                            <div class="flex items-center">
                                <input type="checkbox" id="articlePublished" name="is_published" class="mr-2" checked>
                                <label for="articlePublished" class="text-sm text-gray-700">立即发布</label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="p-4 border-t flex justify-end space-x-3">
                    <button id="cancelAddArticleBtn" class="px-4 py-2 bg-gray-200 text-gray-800 rounded">取消</button>
                    <button id="submitAddArticleBtn" class="px-4 py-2 bg-green-500 text-white rounded">添加文章</button>
                </div>
            </div>
        </div>
    `;
    
    const modalContainer = document.createElement('div');
    modalContainer.id = 'articleModalContainer';
    modalContainer.innerHTML = modalHTML;
    document.body.appendChild(modalContainer);
    
    // 添加事件监听
    document.getElementById('closeAddArticleBtn').addEventListener('click', () => {
        document.getElementById('articleModalContainer').remove();
    });
    
    document.getElementById('cancelAddArticleBtn').addEventListener('click', () => {
        document.getElementById('articleModalContainer').remove();
    });
    
    document.getElementById('submitAddArticleBtn').addEventListener('click', async () => {
        const form = document.getElementById('addArticleForm');
        const title = document.getElementById('articleTitle').value;
        const summary = document.getElementById('articleSummary').value;
        const content = document.getElementById('articleContent').value;
        const isPinned = document.getElementById('articlePinned').checked;
        const isPublished = document.getElementById('articlePublished').checked;
        
        if (!title) {
            showNotification('请填写文章标题', 'error');
            return;
        }
        
        try {
            const response = await fetch('/api/admin/articles', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title,
                    summary,
                    content,
                    is_pinned: isPinned,
                    is_published: isPublished
                })
            });
            
            if (response.ok) {
                document.getElementById('articleModalContainer').remove();
                loadArticlesData();
                showNotification('文章添加成功');
            } else {
                const error = await response.json();
                showNotification(`添加失败: ${error.error || '未知错误'}`, 'error');
            }
        } catch (error) {
            console.error('添加文章错误:', error);
            showNotification('服务器错误，请稍后重试', 'error');
        }
    });
}

// 编辑文章
async function editArticle(articleId) {
    try {
        const response = await fetch(`/api/admin/articles/${articleId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (!response.ok) {
            showNotification('获取文章数据失败', 'error');
            return;
        }
        
        const article = await response.json();
        
        const modalHTML = `
            <div class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50">
                <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl h-5/6 flex flex-col">
                    <div class="p-4 border-b flex justify-between items-center">
                        <h3 class="text-lg font-medium">编辑文章</h3>
                        <button id="closeEditArticleBtn" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="p-4 flex-grow overflow-auto">
                        <form id="editArticleForm" class="space-y-4">
                            <input type="hidden" id="editArticleId" value="${article.id}">
                            
                            <div>
                                <label for="editArticleTitle" class="block text-sm font-medium text-gray-700 mb-1">文章标题</label>
                                <input type="text" id="editArticleTitle" name="title" value="${article.title}" class="w-full px-3 py-2 border rounded-md" required>
                            </div>
                            
                            <div>
                                <label for="editArticleSummary" class="block text-sm font-medium text-gray-700 mb-1">文章摘要</label>
                                <textarea id="editArticleSummary" name="summary" rows="2" class="w-full px-3 py-2 border rounded-md">${article.summary || ''}</textarea>
                            </div>
                            
                            <div>
                                <label for="editArticleContent" class="block text-sm font-medium text-gray-700 mb-1">文章内容 (支持Markdown格式)</label>
                                <textarea id="editArticleContent" name="content" rows="15" class="w-full px-3 py-2 border rounded-md font-mono">${article.content}</textarea>
                            </div>
                            
                            <div class="flex space-x-4">
                                <div class="flex items-center">
                                    <input type="checkbox" id="editArticlePinned" name="is_pinned" class="mr-2" ${article.is_pinned ? 'checked' : ''}>
                                    <label for="editArticlePinned" class="text-sm text-gray-700">置顶文章</label>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="editArticlePublished" name="is_published" class="mr-2" ${article.status === 'published' ? 'checked' : ''}>
                                    <label for="editArticlePublished" class="text-sm text-gray-700">发布文章</label>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="p-4 border-t flex justify-end space-x-3">
                        <button id="cancelEditArticleBtn" class="px-4 py-2 bg-gray-200 text-gray-800 rounded">取消</button>
                        <button id="submitEditArticleBtn" class="px-4 py-2 bg-blue-500 text-white rounded">保存更改</button>
                    </div>
                </div>
            </div>
        `;
        
        const modalContainer = document.createElement('div');
        modalContainer.id = 'articleModalContainer';
        modalContainer.innerHTML = modalHTML;
        document.body.appendChild(modalContainer);
        
        // 添加事件监听
        document.getElementById('closeEditArticleBtn').addEventListener('click', () => {
            document.getElementById('articleModalContainer').remove();
        });
        
        document.getElementById('cancelEditArticleBtn').addEventListener('click', () => {
            document.getElementById('articleModalContainer').remove();
        });
        
        document.getElementById('submitEditArticleBtn').addEventListener('click', async () => {
            const articleId = document.getElementById('editArticleId').value;
            const title = document.getElementById('editArticleTitle').value;
            const summary = document.getElementById('editArticleSummary').value;
            const content = document.getElementById('editArticleContent').value;
            const isPinned = document.getElementById('editArticlePinned').checked;
            const isPublished = document.getElementById('editArticlePublished').checked;
            
            if (!title) {
                showNotification('请填写文章标题', 'error');
                return;
            }
            
            try {
                const response = await fetch(`/api/admin/articles/${articleId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        title,
                        summary,
                        content,
                        is_pinned: isPinned,
                        is_published: isPublished
                    })
                });
                
                if (response.ok) {
                    document.getElementById('articleModalContainer').remove();
                    loadArticlesData();
                    showNotification('文章更新成功');
                } else {
                    const error = await response.json();
                    showNotification(`更新失败: ${error.error || '未知错误'}`, 'error');
                }
            } catch (error) {
                console.error('更新文章错误:', error);
                showNotification('服务器错误，请稍后重试', 'error');
            }
        });
    } catch (error) {
        console.error('编辑文章错误:', error);
        showNotification('服务器错误，请稍后重试', 'error');
    }
}

// 删除文章
async function deleteArticle(articleId) {
    try {
        const response = await fetch(`/api/admin/articles/${articleId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            loadArticlesData();
            showNotification('文章删除成功');
        } else {
            const error = await response.json();
            showNotification(`删除失败: ${error.error || '未知错误'}`, 'error');
        }
    } catch (error) {
        console.error('删除文章错误:', error);
        showNotification('服务器错误，请稍后重试', 'error');
    }
}

// 加载系统设置标签页
function loadSettingsTab() {
    // 隐藏其他内容区域，显示设置内容区域
    document.querySelectorAll('.content-area').forEach(area => {
        area.classList.add('hidden');
    });
    document.getElementById('settingsPage').classList.remove('hidden');
    
    // 加载设置数据
    loadSettingsData();
}

// 加载用户数据
async function loadUsersData() {
    try {
        const usersPage = document.getElementById('usersPage');
        usersPage.innerHTML = '<div class="text-center py-10"><i class="fas fa-spinner fa-spin text-green-500 text-2xl"></i></div>';
        
        const response = await fetch('/api/admin/users', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            renderUsers(data);
        } else {
            usersPage.innerHTML = '<div class="text-center py-10 text-red-500">加载数据失败</div>';
        }
    } catch (error) {
        console.error('加载用户数据错误:', error);
        document.getElementById('usersPage').innerHTML = '<div class="text-center py-10 text-red-500">服务器错误</div>';
    }
}

// 渲染用户列表
function renderUsers(data) {
    const { users, pagination } = data;
    
    const usersHTML = `
        <h2 class="text-2xl font-bold mb-6">用户管理</h2>
        
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">动机分数</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${users.map(user => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${user.email}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <select class="role-select border rounded px-2 py-1 text-sm" data-id="${user.id}">
                                        <option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
                                        <option value="editor" ${user.role === 'editor' ? 'selected' : ''}>编辑</option>
                                        <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
                                    </select>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${new Date(user.created_at).toLocaleString()}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${user.motivation_score}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button class="text-indigo-600 hover:text-indigo-900 mr-3 view-user-btn" data-id="${user.id}">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
            
            <div class="bg-gray-50 px-6 py-3 flex items-center justify-between">
                <div class="text-sm text-gray-500">
                    显示 ${(pagination.page - 1) * pagination.limit + 1} - 
                    ${Math.min(pagination.page * pagination.limit, pagination.total)} 
                    条，共 ${pagination.total} 条
                </div>
                <div class="flex space-x-2">
                    <button id="prevPageUsersBtn" class="px-3 py-1 bg-gray-200 rounded text-gray-600 text-sm" 
                        ${pagination.page <= 1 ? 'disabled' : ''}>
                        上一页
                    </button>
                    <span class="px-3 py-1 bg-gray-200 rounded text-gray-600 text-sm">
                        第 ${pagination.page} 页，共 ${pagination.totalPages} 页
                    </span>
                    <button id="nextPageUsersBtn" class="px-3 py-1 bg-gray-200 rounded text-gray-600 text-sm"
                        ${pagination.page >= pagination.totalPages ? 'disabled' : ''}>
                        下一页
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('usersPage').innerHTML = usersHTML;
    
    // 添加事件监听器
    document.querySelectorAll('.role-select').forEach(select => {
        select.addEventListener('change', function() {
            const userId = this.getAttribute('data-id');
            const newRole = this.value;
            updateUserRole(userId, newRole);
        });
    });
    
    // 分页按钮
    const prevPageBtn = document.getElementById('prevPageUsersBtn');
    const nextPageBtn = document.getElementById('nextPageUsersBtn');
    
    if (prevPageBtn) {
        prevPageBtn.addEventListener('click', () => {
            if (pagination.page > 1) {
                loadUsersWithPage(pagination.page - 1);
            }
        });
    }
    
    if (nextPageBtn) {
        nextPageBtn.addEventListener('click', () => {
            if (pagination.page < pagination.totalPages) {
                loadUsersWithPage(pagination.page + 1);
            }
        });
    }
}

// 根据页码加载用户
async function loadUsersWithPage(page) {
    try {
        const usersPage = document.getElementById('usersPage');
        usersPage.innerHTML = '<div class="text-center py-10"><i class="fas fa-spinner fa-spin text-green-500 text-2xl"></i></div>';
        
        const response = await fetch(`/api/admin/users?page=${page}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            renderUsers(data);
        } else {
            usersPage.innerHTML = '<div class="text-center py-10 text-red-500">加载数据失败</div>';
        }
    } catch (error) {
        console.error('加载用户数据错误:', error);
        document.getElementById('usersPage').innerHTML = '<div class="text-center py-10 text-red-500">服务器错误</div>';
    }
}

// 更新用户角色
async function updateUserRole(userId, role) {
    try {
        const response = await fetch(`/api/admin/users/${userId}/role`, {
            method: 'PATCH',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ role })
        });
        
        if (response.ok) {
            // 成功更新
            alert('用户角色已更新');
        } else {
            const error = await response.json();
            alert(error.error || '更新角色失败');
            // 刷新列表以恢复原始值
            loadUsersData();
        }
    } catch (error) {
        console.error('更新用户角色错误:', error);
        alert('服务器错误，请稍后重试');
        loadUsersData();
    }
}

// 加载习惯标签页
function loadHabitsTab() {
    // 隐藏其他内容区域，显示习惯内容区域
    document.querySelectorAll('.content-area').forEach(area => {
        area.classList.add('hidden');
    });
    document.getElementById('habitsPage').classList.remove('hidden');
    
    // 加载习惯数据
    loadHabitsData();
}

// 加载习惯数据
async function loadHabitsData() {
    try {
        const habitsPage = document.getElementById('habitsPage');
        habitsPage.innerHTML = '<div class="text-center py-10"><i class="fas fa-spinner fa-spin text-green-500 text-2xl"></i></div>';
        
        // 使用Promise.all同时请求数据
        const [recommendationsResponse, habitsResponse, habitsSummaryResponse] = await Promise.all([
            fetchWithAuth('/api/admin/recommendations'),
            fetchWithAuth('/api/admin/habits'),
            fetchWithAuth('/api/admin/habits/summary')
        ]);
        
        if (recommendationsResponse.error || habitsResponse.error || habitsSummaryResponse.error) {
            const error = recommendationsResponse.error || habitsResponse.error || habitsSummaryResponse.error;
            console.error('加载习惯数据错误:', error);
            habitsPage.innerHTML = `<div class="text-center py-10 text-red-500">加载数据失败: ${error}</div>`;
            return;
        }
        
        if (recommendationsResponse.response.ok && habitsResponse.response.ok && habitsSummaryResponse.response.ok) {
            renderHabitsAdmin(
                recommendationsResponse.data, 
                habitsSummaryResponse.data, 
                habitsResponse.data
            );
        } else {
            habitsPage.innerHTML = '<div class="text-center py-10 text-red-500">加载数据失败</div>';
        }
    } catch (error) {
        console.error('加载习惯数据错误:', error);
        document.getElementById('habitsPage').innerHTML = '<div class="text-center py-10 text-red-500">服务器错误</div>';
    }
}

// 渲染习惯管理页面
function renderHabitsAdmin(recommendations, habitsData, allHabits) {
    const habitsHTML = `
        <h2 class="text-2xl font-bold mb-6">习惯管理</h2>
        
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6">
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-blue-100 text-blue-500">
                        <i class="fas fa-tasks text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-500 mb-1">用户总习惯</p>
                        <p class="text-xl font-bold">${habitsData.total_habits || 0}</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-green-100 text-green-500">
                        <i class="fas fa-bookmark text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-500 mb-1">推荐习惯</p>
                        <p class="text-xl font-bold">${recommendations.length}</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-yellow-100 text-yellow-500">
                        <i class="fas fa-th-list text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-500 mb-1">习惯分类</p>
                        <p class="text-xl font-bold">${habitsData.categories ? habitsData.categories.length : 0}</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-purple-100 text-purple-500">
                        <i class="fas fa-archive text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-500 mb-1">已归档习惯</p>
                        <p class="text-xl font-bold">${habitsData.archived_habits || 0}</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 全部用户习惯列表 -->
        <div class="bg-white rounded-lg shadow overflow-hidden mb-6">
            <div class="p-4 border-b">
                <h3 class="text-lg font-medium">用户习惯列表</h3>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">难度</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${allHabits && allHabits.length > 0 ? allHabits.map(habit => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${habit.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${habit.title}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${habit.user_email}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${getDifficultyText(habit.difficulty)}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${new Date(habit.created_at).toLocaleString()}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    ${habit.is_archived ? 
                                        '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">已归档</span>' : 
                                        '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">进行中</span>'
                                    }
                                </td>
                            </tr>
                        `).join('') : `
                            <tr>
                                <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">暂无习惯数据</td>
                            </tr>
                        `}
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 推荐习惯管理 -->
        <div class="bg-white rounded-lg shadow overflow-hidden mb-6">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="text-lg font-medium">推荐习惯管理</h3>
                <button id="addRecommendationBtn" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors">
                    <i class="fas fa-plus mr-2"></i>添加推荐
                </button>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">图标</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">难度</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${recommendations.map(habit => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${habit.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="h-8 w-8 rounded-full flex items-center justify-center" style="background-color: ${habit.color}">
                                        <i class="fas fa-${habit.icon} text-white"></i>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${habit.title}</td>
                                <td class="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">${habit.description}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${getDifficultyText(habit.difficulty)}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${habit.category}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button class="text-indigo-600 hover:text-indigo-900 mr-3 edit-recommendation-btn" data-id="${habit.id}">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="text-red-600 hover:text-red-900 delete-recommendation-btn" data-id="${habit.id}">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 最近创建的习惯 -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="p-4 border-b">
                <h3 class="text-lg font-medium">最近创建的习惯</h3>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${habitsData.recent_habits && habitsData.recent_habits.map(habit => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${habit.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${habit.title}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${habit.user_email}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${new Date(habit.created_at).toLocaleString()}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    ${habit.is_archived ? 
                                        '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">已归档</span>' : 
                                        '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">进行中</span>'
                                    }
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    document.getElementById('habitsPage').innerHTML = habitsHTML;
    
    // 添加事件监听器
    document.getElementById('addRecommendationBtn').addEventListener('click', showAddRecommendationModal);
    
    document.querySelectorAll('.edit-recommendation-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const habit = recommendations.find(h => h.id == id);
            if (habit) {
                showEditRecommendationModal(habit);
            }
        });
    });
    
    document.querySelectorAll('.delete-recommendation-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            if (confirm('确定要删除这个推荐习惯吗？')) {
                deleteRecommendation(id);
            }
        });
    });
}

// 根据难度级别获取文本描述
function getDifficultyText(difficulty) {
    switch(parseInt(difficulty)) {
        case 1: return '非常简单';
        case 2: return '简单';
        case 3: return '中等';
        case 4: return '困难';
        case 5: return '非常困难';
        default: return '未知';
    }
}

// 显示添加推荐习惯的模态框
function showAddRecommendationModal() {
    const modalHTML = `
        <div class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
                <div class="p-4 border-b">
                    <h3 class="text-lg font-medium">添加推荐习惯</h3>
                </div>
                <div class="p-4">
                    <form id="addRecommendationForm">
                        <div class="mb-4">
                            <label for="title" class="block text-sm font-medium text-gray-700 mb-1">习惯名称</label>
                            <input type="text" id="title" name="title" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        
                        <div class="mb-4">
                            <label for="description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                            <textarea id="description" name="description" rows="3" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required></textarea>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label for="icon" class="block text-sm font-medium text-gray-700 mb-1">图标</label>
                                <input type="text" id="icon" name="icon" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" placeholder="例如: running" required>
                            </div>
                            
                            <div>
                                <label for="color" class="block text-sm font-medium text-gray-700 mb-1">颜色</label>
                                <input type="text" id="color" name="color" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" placeholder="例如: #ff5500" required>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label for="difficulty" class="block text-sm font-medium text-gray-700 mb-1">难度</label>
                                <select id="difficulty" name="difficulty" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                                    <option value="1">非常简单</option>
                                    <option value="2">简单</option>
                                    <option value="3">中等</option>
                                    <option value="4">困难</option>
                                    <option value="5">非常困难</option>
                                </select>
                            </div>
                            
                            <div>
                                <label for="category" class="block text-sm font-medium text-gray-700 mb-1">分类</label>
                                <input type="text" id="category" name="category" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" placeholder="例如: 健康" required>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" id="cancelAddBtn" class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors">
                                添加
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `;
    
    // 添加模态框到页面
    const modalContainer = document.createElement('div');
    modalContainer.id = 'modalContainer';
    modalContainer.innerHTML = modalHTML;
    document.body.appendChild(modalContainer);
    
    // 添加事件监听器
    document.getElementById('cancelAddBtn').addEventListener('click', () => {
        document.getElementById('modalContainer').remove();
    });
    
    document.getElementById('addRecommendationForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = {
            title: document.getElementById('title').value,
            description: document.getElementById('description').value,
            icon: document.getElementById('icon').value,
            color: document.getElementById('color').value,
            difficulty: document.getElementById('difficulty').value,
            category: document.getElementById('category').value
        };
        
        addRecommendation(formData);
    });
}

// 显示编辑推荐习惯的模态框
function showEditRecommendationModal(habit) {
    const modalHTML = `
        <div class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
                <div class="p-4 border-b">
                    <h3 class="text-lg font-medium">编辑推荐习惯</h3>
                </div>
                <div class="p-4">
                    <form id="editRecommendationForm">
                        <input type="hidden" id="editId" value="${habit.id}">
                        
                        <div class="mb-4">
                            <label for="editTitle" class="block text-sm font-medium text-gray-700 mb-1">习惯名称</label>
                            <input type="text" id="editTitle" name="title" value="${habit.title}" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        
                        <div class="mb-4">
                            <label for="editDescription" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                            <textarea id="editDescription" name="description" rows="3" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>${habit.description}</textarea>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label for="editIcon" class="block text-sm font-medium text-gray-700 mb-1">图标</label>
                                <input type="text" id="editIcon" name="icon" value="${habit.icon}" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                            </div>
                            
                            <div>
                                <label for="editColor" class="block text-sm font-medium text-gray-700 mb-1">颜色</label>
                                <input type="text" id="editColor" name="color" value="${habit.color}" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label for="editDifficulty" class="block text-sm font-medium text-gray-700 mb-1">难度</label>
                                <select id="editDifficulty" name="difficulty" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                                    <option value="1" ${habit.difficulty == 1 ? 'selected' : ''}>非常简单</option>
                                    <option value="2" ${habit.difficulty == 2 ? 'selected' : ''}>简单</option>
                                    <option value="3" ${habit.difficulty == 3 ? 'selected' : ''}>中等</option>
                                    <option value="4" ${habit.difficulty == 4 ? 'selected' : ''}>困难</option>
                                    <option value="5" ${habit.difficulty == 5 ? 'selected' : ''}>非常困难</option>
                                </select>
                            </div>
                            
                            <div>
                                <label for="editCategory" class="block text-sm font-medium text-gray-700 mb-1">分类</label>
                                <input type="text" id="editCategory" name="category" value="${habit.category}" class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500" required>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" id="cancelEditBtn" class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors">
                                更新
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `;
    
    // 添加模态框到页面
    const modalContainer = document.createElement('div');
    modalContainer.id = 'modalContainer';
    modalContainer.innerHTML = modalHTML;
    document.body.appendChild(modalContainer);
    
    // 添加事件监听器
    document.getElementById('cancelEditBtn').addEventListener('click', () => {
        document.getElementById('modalContainer').remove();
    });
    
    document.getElementById('editRecommendationForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const id = document.getElementById('editId').value;
        const formData = {
            title: document.getElementById('editTitle').value,
            description: document.getElementById('editDescription').value,
            icon: document.getElementById('editIcon').value,
            color: document.getElementById('editColor').value,
            difficulty: document.getElementById('editDifficulty').value,
            category: document.getElementById('editCategory').value
        };
        
        updateRecommendation(id, formData);
    });
}

// 添加推荐习惯
async function addRecommendation(data) {
    try {
        const response = await fetch('/api/admin/recommendations', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            // 关闭模态框
            document.getElementById('modalContainer').remove();
            // 显示成功消息
            alert('推荐习惯添加成功');
            // 重新加载数据
            loadHabitsData();
        } else {
            const error = await response.json();
            alert(error.error || '添加失败');
        }
    } catch (error) {
        console.error('添加推荐习惯错误:', error);
        alert('服务器错误，请稍后重试');
    }
}

// 更新推荐习惯
async function updateRecommendation(id, data) {
    try {
        const response = await fetch(`/api/admin/recommendations/${id}`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            showNotification('推荐习惯更新成功');
            return await response.json();
        } else {
            const error = await response.json();
            showNotification(`更新失败: ${error.error || '未知错误'}`, 'error');
            throw new Error(error.error || '更新推荐习惯失败');
        }
    } catch (error) {
        console.error('更新推荐习惯错误:', error);
        showNotification('服务器错误，请稍后重试', 'error');
        throw error;
    }
}

// 删除推荐习惯
async function deleteRecommendation(id) {
    try {
        const response = await fetch(`/api/admin/recommendations/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            showNotification('推荐习惯删除成功');
            return true;
        } else {
            const error = await response.json();
            showNotification(`删除失败: ${error.error || '未知错误'}`, 'error');
            return false;
        }
    } catch (error) {
        console.error('删除推荐习惯错误:', error);
        showNotification('服务器错误，请稍后重试', 'error');
        return false;
    }
}

// 创建新文章
async function createArticle(title, content, isPinned, isPublished) {
    try {
        const response = await fetch('/api/admin/articles', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                title,
                content,
                is_pinned: isPinned,
                is_published: isPublished
            })
        });
        
        if (response.ok) {
            const article = await response.json();
            return article;
        } else {
            const error = await response.json();
            throw new Error(error.error || '创建文章失败');
        }
    } catch (error) {
        console.error('创建文章错误:', error);
        throw error;
    }
}

// 显示自动消失的提示消息
function showNotification(message, type = 'success') {
    // 移除已有的通知
    const existingNotification = document.getElementById('adminNotification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // 创建通知元素
    const notification = document.createElement('div');
    notification.id = 'adminNotification';
    
    // 设置样式
    if (type === 'success') {
        notification.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-lg z-50 transition-all duration-300';
    } else {
        notification.className = 'fixed top-4 right-4 bg-red-500 text-white px-4 py-2 rounded shadow-lg z-50 transition-all duration-300';
    }
    
    notification.textContent = message;
    
    // 添加到DOM
    document.body.appendChild(notification);
    
    // 设置自动消失
    const duration = type === 'success' ? 1500 : 2500;
    setTimeout(() => {
        notification.classList.add('opacity-0');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, duration);
}

// 初始化
document.addEventListener('DOMContentLoaded', initAdminPanel); 